package com.jingdianjichi.wx.controller;

import com.jingdianjichi.wx.handler.WxChatMsgFactory;
import com.jingdianjichi.wx.handler.WxChatMsgHandler;
import com.jingdianjichi.wx.utils.MessageUtil;
import com.jingdianjichi.wx.utils.SHA1;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

@Slf4j
@RestController
public class CollBackController {

    private static final String token="saddsasda";

    @Resource
    private WxChatMsgFactory wxChatMsgFactory;

    @RequestMapping("/test")
    public void test(){
        System.out.println("test");
    }

    @GetMapping("callback")
    public String callback(@RequestParam("signature") String signature
                           , @RequestParam("timestamp") String timestamp
                           , @RequestParam("nonce") String nonce
                           , @RequestParam("echostr") String echostr
    ){
        log.info("各参数", signature, timestamp, nonce, echostr);
        String sha1 = SHA1.getSHA1(token, timestamp, nonce,"");
        if(signature.equals(sha1)){
            return echostr;
        }
        return "unknown";
    }

    @PostMapping(value = "callback",produces = "application/xml;charset=UTF-8")
    public String callback(@RequestBody String body,
            @RequestParam("signature") String signature
            , @RequestParam("timestamp") String timestamp
            , @RequestParam("nonce") String nonce
            , @RequestParam(value = "msg_signature",required = false) String msgSignature
    ){
        log.info("各参数", body,signature, timestamp, nonce);
        Map<String, String> stringStringMap = MessageUtil.parseXml(body);
        String msgType = stringStringMap.get("MsgType");
        String event = stringStringMap.get("Event")==null ? "" : stringStringMap.get("Event");
        log.info("msgtype:" + msgType + ",event:" + event);
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(msgType);
        if(!StringUtils.isEmpty(event)){
            stringBuilder.append(".");
            stringBuilder.append(event);
        }
        String msgTypeKet=stringBuilder.toString();
        WxChatMsgHandler handlerByMsgType = wxChatMsgFactory.getHandlerByMsgType(msgTypeKet);
        if(Objects.isNull(handlerByMsgType)){
            return "unknown";
        }
        String s = handlerByMsgType.dealMsg(stringStringMap);
        return s;
    }
}
